package com.cswnode.Controller.interceptor;

import com.cswnode.Annotations.LoginJudgment;
import com.cswnode.Util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author csw
 * @create 2020/9/20 10:43
 */
//验证用户是否登陆
@Component
public class LoginJudgmentInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;

    @Value("${server.servlet.context-path}")
    private String ContextPath;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断拦截的是否为方法
        if (handler instanceof HandlerMethod){
            //如果属于进行转行
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //获得方法
            Method method = handlerMethod.getMethod();
            //获得包含loginJudgment注解的方法
            LoginJudgment annotation = method.getAnnotation(LoginJudgment.class);
            //如果获得包含loginJudgment注解的方法不为空，并且获得的用户为空
            //表示该请求需要用户登陆才能访问.
            //用户未登录，所以需要拦截该请求
            if (annotation != null && hostHolder.getUser() == null){
                response.sendRedirect(ContextPath + "/login");
                return false;
            }
        }
        return true;
    }
}
